package org.sundatagroup.aurora.monitor.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.sundatagroup.aurora.core.controller.IJsonResultController;
import org.sundatagroup.aurora.show.entity.status.IStatusEntity;
import org.sundatagroup.aurora.show.service.ScreenStatusService;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

/**
 * <p>查询展示屏状态的 Controller
 * <p>采用 Ajax 请求
 * </p>
 * 
 * @version 0.2.0
 * 
 * @author Zdream
 * @date 2018-05-25
 * @since 0.1.1
 */
@RequestMapping("/aurora")
@Controller
public class StatusController implements IJsonResultController {
	
	@Autowired
	ScreenStatusService statusQuerier;

	/**
	 * 监控器接口, 用于监控器主动发起请求, 查询展示屏状态的接口. (后面要放到监视器部分. 现在暂时放在这里)
	 * @param sid
	 *   screen ID 屏幕号
	 * @return
	 *   用 json 格式返回状态数据<br>
	 *   若未找到, 返回 result: false
	 * @since 0.1
	 * @version 0.1.1
	 */
	@RequestMapping(value = "monitor/status/{sid}",
			method = RequestMethod.GET,
			produces = {"application/json"})
	@ResponseBody
	public String spacificStatus(@PathVariable String sid){
		IStatusEntity status = statusQuerier.query(sid);
		if (status == null) {
			return rawResultJsonObject(false).toString();
		}
		
		JsonObject jo = rawResultJsonObject();
		jo.add("data", status.toJson());
		return jo.toString();
	}

	/**	
	 * 监控器接口, 用于监控器主动发起请求, 查询所有展示屏状态的接口.
	 * @return
	 *   返回自动转换的json数组,包含所有显示屏的状态<br>
	 *   若未找到, 返回 result: false
	 * @since 0.1.1
	 */
	@RequestMapping(value = "monitor/status/all",
			method = RequestMethod.GET,
			produces = {"application/json"})
	@ResponseBody
	public String allStatus(){
		List<IStatusEntity> allStatus = statusQuerier.queryAll();
		
		JsonObject jo = rawResultJsonObject();
		JsonArray array = new JsonArray(allStatus.size());
		allStatus.forEach((status) -> {
			array.add(status.toJson());
		});
		
		jo.add("datas", array);
		return jo.toString();
	}

}
